package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.GoodsFile;
import com.neusoft.neuiotms.dcam.fixed.model.QGoodsFile;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedGoodsFileRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedGoodsFileRepositoryImpl extends AbstractRepository
        implements CustomizedGoodsFileRepository {

    @Override
    public Page<GoodsFile> search(final Pageable pageable, final Searchable searchable) {
        final QGoodsFile qGoodsFile = QGoodsFile.goodsFile;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<GoodsFile> query = this.query().selectFrom(qGoodsFile);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return GoodsFile.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QGoodsFile qGoodsFile = QGoodsFile.goodsFile;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.or(super.containsStr(qGoodsFile.name, searchable, "name"));
            where.or(super.containsStr(qGoodsFile.specification, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("spareTypeCode"))) {
            where.and(super.equalsStr(qGoodsFile.spareType.code, searchable, "spareTypeCode"));//类型code
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("specification"))) {
            where.and(super.equalsStr(qGoodsFile.specification, searchable, "specification"));//类型code
        }

        if (searchable.hasKey("assetCode")) {
            where.and(super.equalsStr(qGoodsFile.assetCode, searchable, "assetCode"));
        }

        return where;
    }

}
